﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace MySilverlightAlbum
{
    [TemplatePart(Name = ProgressBarControl.TP_CANVAS_PART, Type = typeof(FrameworkElement))]
    public class ProgressBarControl: Control
    {
        private const string                            TP_CANVAS_PART = "rootLayout";
        private double                                  m_progress;

        public ProgressBarControl(
        )
        {
            this.DefaultStyleKey = typeof(ProgressBarControl);
            this.DataContext = this;
        }

        public FrameworkElement RootCanvas
        {
            get;
            set;
        }

        public static DependencyProperty ProgressBarWidthProperty = DependencyProperty.Register(
            "ProgressBarWidth", typeof(double), typeof(ProgressBarControl), 
            new PropertyMetadata(0.0, new PropertyChangedCallback(ProgressBarWidthPropertyChanged)));

        public static void ProgressBarWidthPropertyChanged(
            DependencyObject                            d, 
            DependencyPropertyChangedEventArgs          e
        )
        {
            ((ProgressBarControl) d).OnProgressBarWidthPropertyChanged(e);
        }

        protected virtual void OnProgressBarWidthPropertyChanged(
            DependencyPropertyChangedEventArgs          e
        )
        {
        }

        public double Progress
        {
            get
            {
                return m_progress;
            }

            set
            {
                if (value > 100)
                {
                    value = 100;
                }
                else if (value < 0)
                {
                    value = 0;
                }

                ProgressBarWidth = (this.Width - 8) * (value / 100.0);
                m_progress = value;
            }
        }
        
        public double ProgressBarWidth
        {
            get
            {
                return (double) GetValue(ProgressBarWidthProperty);
            }

            set
            {
                SetValue(ProgressBarWidthProperty, value);
            }
        }

        public override void OnApplyTemplate(
        )
        {
            base.OnApplyTemplate();

            RootCanvas = (FrameworkElement) GetTemplateChild(TP_CANVAS_PART);
        }
    }
}
